import React from 'react';
import { connect } from 'dva';
import { FixedButtonC, FirstHeaderC, PrimaryGhostC, PrimaryC } from '../../../../comps';
import styles from '../index.less';
//组件引入
import BaseInfo from './BaseInfo'; //基本信息
import ReportInfo from './ReportInfo'; //监管报表信息
import AssetPackage from './AssetPackage'; //资产包
import Redemption from './redemption'; //赎回计息
import moment from 'moment';
import { message } from 'antd';

class FormContent extends React.Component {
  constructor() {
    super();
    this.state = {
      formDatas: {
        baseInfo: {}, //基本信息
        files: [], //资产包
        zgtzptNonstandarCashFlows: [], //赎回计息
      },
      //需要根据基本信息改变报表信息
      baseBaseInfoChangeReport: {
        //资产类别
        assetType: undefined,
        //担保方式
        guaranteeWay: undefined,
        //起息日
        startDate: undefined,
        //到期日
        endDate: undefined,
        //金额
        issueScale: undefined,
        //利率类型
        rateType: undefined,
        //计息基础
        interestBasis: undefined,
        //付息频率
        interestRate: undefined,
        //项目收益率（利率）
        fixedRate: undefined,
        //份额面值
        parTotalValue: undefined,
      },
      //需要根据报表信息改变基本信息
      baseReportChangeBaseInfo: {
        //是否有预期收益率
        jgbb_sfyyqsyl: undefined,
      },
    };
  }
  componentDidMount() {
    //获取主页面传入进来的form的值
    this.setState({
      formDatas: this.props.formDatas,
      baseBaseInfoChangeReport: {
        assetType: this.props.formDatas.baseInfo?.assetType || undefined,
        guaranteeWay: this.props.formDatas.baseInfo?.guaranteeWay || undefined,
        startDate: this.props.formDatas.baseInfo?.startDate ? moment(new Date(this.props.formDatas.baseInfo?.startDate)) : undefined,
        endDate: this.props.formDatas.baseInfo?.endDate ? moment(new Date(this.props.formDatas.baseInfo?.endDate)) : undefined,
        //金额
        issueScale: this.props.formDatas.baseInfo?.issueScale || undefined,
        //利率类型
        rateType: this.props.formDatas.baseInfo?.rateType || undefined,
        //计息基础
        interestBasis: this.props.formDatas.baseInfo?.interestBasis || undefined,
        //付息频率
        interestRate: this.props.formDatas.baseInfo?.interestRate || undefined,
        //项目收益率（利率）
        fixedRate: this.props.formDatas.baseInfo?.fixedRate || undefined,
        //份额面值
        parTotalValue: this.props.formDatas.baseInfo?.parTotalValue || undefined,
      },
      // baseReportChangeBaseInfo:{
      //     //是否有预期收益率
      //     jgbb_sfyyqsyl:this.props.formDatas.reportInfo?.jgbb_sfyyqsyl || undefined
      // }
    });
  }
  UNSAFE_componentWillReceiveProps(nextProps) {
    if (JSON.stringify(nextProps.formDatas) != JSON.stringify(this.props.formDatas)) {
      this.setState({
        formDatas: nextProps.formDatas,
        baseBaseInfoChangeReport: {
          assetType: nextProps.formDatas.baseInfo?.assetType || undefined,
          guaranteeWay: nextProps.formDatas.baseInfo?.guaranteeWay || undefined,
          startDate: nextProps.formDatas.baseInfo?.startDate ? moment(new Date(nextProps.formDatas.baseInfo?.startDate)) : undefined,
          endDate: nextProps.formDatas.baseInfo?.endDate ? moment(new Date(nextProps.formDatas.baseInfo?.endDate)) : undefined,
          //金额
          issueScale: nextProps.formDatas.baseInfo?.issueScale || undefined,
          //利率类型
          rateType: nextProps.formDatas.baseInfo?.rateType || undefined,
          //计息基础
          interestBasis: nextProps.formDatas.baseInfo?.interestBasis || undefined,
          //付息频率
          interestRate: nextProps.formDatas.baseInfo?.interestRate || undefined,
          //项目收益率（利率）
          fixedRate: nextProps.formDatas.baseInfo?.fixedRate || undefined,
          //份额面值
          parTotalValue: this.props.formDatas.baseInfo?.parTotalValue || undefined,
        },
        // baseReportChangeBaseInfo:{
        //     //是否有预期收益率
        //     jgbb_sfyyqsyl:nextProps.formDatas.reportInfo?.jgbb_sfyyqsyl || undefined
        // }
      });
    }
  }
  //点击取消
  cancel = () => {
    this.props.CancelFn && this.props.CancelFn();
  };
  //循环对象中的值 如果有undefied转化成null
  circleData = (objs) => {
    if (!!objs) {
      for (var i in objs) {
        if (objs[i] == undefined) {
          objs[i] = null;
        }
      }
    }
    return objs;
  };
  //点击确定
  confirmOk = () => {
    const {
      formDatas: { id },
      pageType,
      dispatch,
      activeKey,
      type,
    } = this.props;
    let files = type != 'workStation' ? this.assetPackages.getInfo() : []; //资产包
    let redempArrs = new Promise((resolve, reject) => {
      if (activeKey == '1') {
        this.redemps.getInfo((values) => {
          if (values) {
            resolve(values);
          }
        });
      } else {
        resolve([]);
      }
    });
    let baseInfos = new Promise((resolve, reject) => {
      this.baseInfos.getInfo()((values) => {
        resolve(values);
      });
    });
    // let reports = new Promise((resolve,reject)=>{
    //     this.reportInfos.getInfo()(values=>{
    //         resolve(values)
    //     })
    // })
    let sendPParams;
    Promise.all([baseInfos, redempArrs]).then((reportName) => {
      let params = {
        baseInfo: this.circleData(reportName[0]),
        files: files ? files : [], //资产包
        zgtzptNonstandarCashFlows: reportName[1],
      };
      if (pageType == 'add') {
        sendPParams = {
          ...params,
        };
      } else if (pageType == 'edit') {
        sendPParams = {
          ...params,
          id: id,
        };
      }
      if (activeKey == '1') {
        //只有在资产的时候 才会进行判断
        if (!params.baseInfo.fixedRate && !params.baseInfo.jgbb_jzllzl && params.baseInfo.rateType == 0) {
          message.warning('项目收益率与基准利率种类不得同时为空!');
          return false;
        }
      }

      dispatch({
        type: 'nonstandarmaintenanceNewM/saveData',
        payload: {
          ...sendPParams,
        },
        callback: (res) => {
          if (res) {
            this.props?.saveReshList && this.props.saveReshList(activeKey);
          }
        },
      });
    });
  };
  //资产更改资产类别
  onAssetTypeChange = (e) => {
    this.setState({
      baseBaseInfoChangeReport: {
        ...this.state.baseBaseInfoChangeReport,
        assetType: e,
      },
    });
  };
  //更改担保方式
  onGuaranteeWayChange = (e) => {
    this.setState({
      baseBaseInfoChangeReport: {
        ...this.state.baseBaseInfoChangeReport,
        guaranteeWay: e,
      },
    });
  };
  //更改起息日
  changeStartDate = (e) => {
    this.setState({
      baseBaseInfoChangeReport: {
        ...this.state.baseBaseInfoChangeReport,
        startDate: e,
      },
    });
  };
  //更改到期日
  changeEndDate = (e) => {
    this.setState({
      baseBaseInfoChangeReport: {
        ...this.state.baseBaseInfoChangeReport,
        endDate: e,
      },
    });
  };

  //更改基本信息
  onBaseInfoChange = (e) => {
    if (e.startDate) {
      e.startDate = moment(e.startDate).format('YYYY-MM-DD');
    }
    if (e.endDate) {
      e.endDate = moment(e.endDate).format('YYYY-MM-DD');
    }

    this.setState({
      baseBaseInfoChangeReport: {
        ...this.state.baseBaseInfoChangeReport,
        ...e,
      },
    });
  };
  //设置付息金额不可编辑的标志
  formData = (data) => {
    data &&
      data.map((item) => {
        if (moment(item.endDate) < moment()) {
          //到期日小于当前日期 则不可修改
          item.disable = 1;
        }
      });
    return data;
  };

  render() {
    const {
      formDatas: { baseInfo, zgtzptNonstandarCashFlows, files, id },
      baseBaseInfoChangeReport,
      baseReportChangeBaseInfo,
    } = this.state;
    const { pageType, activeKey, loading, type } = this.props;
    let status = {
      add: '新增',
      edit: '编辑',
      view: '查看',
    };
    const titles = activeKey == '1' ? '非标准化债权类资产' : '非标准化债权类投资'; //
    const disableStatus = pageType == 'view'; //是否是查看得状态
    return (
      <div>
        {/* 工作台不展示一级标题 */}
        {type != 'workStation' ? <FirstHeaderC title={`${titles}-${status[pageType]}`}></FirstHeaderC> : ''}
        <FixedButtonC
          style={{ borderTop: '1px solid rgba(67, 118, 255, 0.1)' }}
          topHtml={
            <>
              <BaseInfo
                baseInfo={baseInfo}
                activeKey={activeKey}
                disableStatus={disableStatus}
                onRef={(ref) => (this.baseInfos = ref)}
                pageType={pageType}
                baseReportChangeBaseInfo={baseReportChangeBaseInfo}
                baseBaseInfoChangeReport={baseBaseInfoChangeReport}
                onBaseInfoChange={this.onBaseInfoChange}
              ></BaseInfo>
              {
                //只有资产得时候有赎回计息
                activeKey == '1' && (
                  <div style={{ marginBottom: '20px' }}>
                    <Redemption
                      {...baseBaseInfoChangeReport}
                      id={id}
                      initInfo={this.formData(zgtzptNonstandarCashFlows)}
                      disableStatus={disableStatus}
                      onRef={(ref) => (this.redemps = ref)}
                    ></Redemption>
                  </div>
                )
              }
              {type != 'workStation' ? (
                <AssetPackage pageType={pageType} files={files} activeKey={activeKey} disableStatus={disableStatus} onRef={(ref) => (this.assetPackages = ref)}></AssetPackage>
              ) : (
                ''
              )}
            </>
          }
          bottomHtml={
            <div className={styles.borderLine}>
              <PrimaryGhostC title={'取消'} onClick={this.cancel}></PrimaryGhostC>
              {!disableStatus && <PrimaryC title={'确定'} loading={loading} onClick={this.confirmOk}></PrimaryC>}
            </div>
          }
        ></FixedButtonC>
      </div>
    );
  }
}
export default connect(({ nonstandarmaintenanceNewM, loading }) => ({
  nonstandarmaintenanceNewM,
  loading: loading.effects['nonstandarmaintenanceNewM/saveData'],
}))(FormContent);
